import { sum, getMultiLang } from 'nc-lightapp-front';
import React, { Component } from 'react';
import ApproveDetail from 'uap/common/components/ApproveDetail';
import NCUploader from 'uap/common/components/NCUploader';


class BillCardStyle extends Component {

    constructor(props) {
        super();
        this.state = {
            sumText: '', //仅做触发cardTable render使用
            multiLang: {},
            tablesCount: {

            }
        }

        window.__ssc_BillStyleVar = {
            tablesCount: {

            }
        }
        let tablesCount = window.__ssc_BillStyleVar.tablesCount;
        const cardTable = props.cardTable;

        window.__ssc_BillStyleVar.tableRowAndItemCount = (areaId, actionType, factor) => { //cardTable 的afterEvent里也会用到这个函数
            let tableCountObj = tablesCount[areaId];
            if (!tableCountObj) {
                return;
            }
            let rowIndex = null;
            let rowObj = null;
            let attrObj = null;
            let allRow = 0;
            let configError = false;
            let changedRow = null;
            switch (actionType) {
                case 'rowChange':
                    changedRow = factor[0];
                    let newValue = changedRow.newvalue.value;
                    let oldValue = changedRow.oldvalue.value;
                    // tableCountObj.totalItemCount = sum(+(tableCountObj.totalItemCount + '').replace(/,/g, ''), -oldValue, newValue)
                    tableCountObj.totalItemCount = sum(+(String(tableCountObj.totalItemCount || 0)), -oldValue, newValue)
                    break;
                case 'add':
                    if (tableCountObj.totalItemCode) {
                        let areaTpl = props.meta.getMeta()[areaId].items.find((item) => {
                            return item.attrcode == tableCountObj.totalItemCode;
                        })
                        if (areaTpl) {
                            tableCountObj.totalItemCount = sum(+(tableCountObj.totalItemCount + '').replace(/,/g, ''), areaTpl.initialvalue && +areaTpl.initialvalue.value ? areaTpl.initialvalue.value : 0);
                        } else {
                            configError = true;
                        }
                    }
                    tableCountObj.rowCount += 1;
                    break;
                case 'copy':
                    if (tableCountObj.totalItemCode) {
                        rowIndex = factor;
                        rowObj = props.cardTable.getDataByIndex(areaId, rowIndex);
                        attrObj = rowObj.values[tableCountObj.totalItemCode];
                        if (attrObj) {
                            tableCountObj.totalItemCount = sum(+(tableCountObj.totalItemCount + '').replace(/,/g, ''), attrObj.value)
                        } else {
                            configError = true;
                        }
                    }
                    tableCountObj.rowCount += 1;

                    break;
                case 'del':
                    if (tableCountObj.totalItemCode) {
                        rowIndex = factor;
                        rowObj = props.cardTable.getDataByIndex(areaId, rowIndex);
                        attrObj = rowObj.values[tableCountObj.totalItemCode];
                        if (attrObj) {
                            tableCountObj.totalItemCount = sum(+(tableCountObj.totalItemCount + '').replace(/,/g, ''), -attrObj.value)
                        } else {
                            configError = true;
                        }
                    }
                    tableCountObj.rowCount -= 1;
                    break;
                case 'all':
                    allRow = factor || 0;
                    if (tableCountObj.totalItemCode) {
                        let total = 0;
                        let tempNum = [total];
                        try {
                            allRow.forEach((row) => {
                                if (row.status != 3) {
                                    let itemObj = row.values[tableCountObj.totalItemCode];
                                    let value = +itemObj.value;
                                    if (value || value === 0) {
                                        tempNum.push(value);
                                    }
                                }
                            })
                            total = sum.apply(null, tempNum);
                            if (tableCountObj.totalItemCount != total) {
                                tableCountObj.totalItemCount = total;
                            }
                        } catch (e) {
                            configError = true;
                        }
                    }
                    tableCountObj.rowCount = allRow.length;
                    break;
            }
            if (configError) {
                console.error(`totalItemCode配置异常：未找到 ${tableCountObj.totalItemCode} 字段`, `区域id:${areaId}`);
            }

            if (tableCountObj.totalBarDom) {
                let text = tableCountObj.rowCount;
                if (tableCountObj.totalItemCode) {
                    text = text + "，" + tableCountObj.totalItemCount
                }
                this.setState({
                    sumText: areaId + text
                })

            }
        }

        //重写cardTable 增加行方法
        let oldAddRow = cardTable.addRow;
        cardTable.addRow = (...param) => {
            window.__ssc_BillStyleVar.tableRowAndItemCount(param[0], 'add');
            oldAddRow.apply(cardTable, param);
        }

        //复制行
        let oldPasteRow = cardTable.pasteRow;
        cardTable.pasteRow = (...param) => {
            let orgiRowIndex = param[1];
            window.__ssc_BillStyleVar.tableRowAndItemCount(param[0], 'copy', orgiRowIndex);
            oldPasteRow.apply(cardTable, param);
        }


        //重写cardTable 删除行方法
        let oldDelRowsByIndex = cardTable.delRowsByIndex;
        cardTable.delRowsByIndex = (...param) => {
            let delRowIndex = param[1];
            window.__ssc_BillStyleVar.tableRowAndItemCount(param[0], 'del', delRowIndex);
            oldDelRowsByIndex.apply(cardTable, param);
        }

        
        let oldDelRowByRowId = cardTable.delRowByRowId;
        cardTable.delRowByRowId = (...param) => {
            let rowid = param[1];
            let delRowIndex
            const allRows = cardTable.getVisibleRows(param[0])
            allRows.forEach((row,index) => {
                if(row.rowid === rowid) {
                    delRowIndex = index
                }
            })
            window.__ssc_BillStyleVar.tableRowAndItemCount(param[0], 'del', delRowIndex);
            oldDelRowByRowId.apply(cardTable, [param[0], param[1]]);
        }
        let oldUpdateDataByRowId = cardTable.updateDataByRowId;
        cardTable.updateDataByRowId = (...param) => {
            let oldAllRow = cardTable.getAllRows(param[0]);
            let allRow = param[1].rows;
            if (oldAllRow.length != allRow.length) {
                let rowJson = {};
                //之前的id，修改成rowid
                allRow.forEach((row) => {
                    rowJson[row.rowid] = row;
                })
                let newRows = []
                oldAllRow.forEach((row) => {
                    //过滤掉删除项
                    if(row.status !== '3') {
                        if (rowJson[row.rowid]) {
                            newRows.push(rowJson[row.rowid])
                        } else {
                            newRows.push(row)
                        }
                    }
                })
                allRow = newRows;
            }
            window.__ssc_BillStyleVar.tableRowAndItemCount(param[0], 'all', allRow);
            oldUpdateDataByRowId.apply(cardTable, param)
        }

        //重写cardTable 设置数据方法
        let oldSetTableData = cardTable.setTableData;
        cardTable.setTableData = (...param) => {
            let allRow = param[1].rows;
            window.__ssc_BillStyleVar.tableRowAndItemCount(param[0], 'all', allRow);
            oldSetTableData.apply(cardTable, param);
        }
        cardTable.setTableDataWithResetInitValue = (...param) => {
            //根据模板，重设默认值
            //重设原则：1、原始模板表格字段中存在initalvalue属性，则进行重设。2、如果字段类型是number，则仅重设scale字段。
            let bodyArea = param[0];
            let meta = this.props.meta;
            let metaData = meta.getMeta();
            if (param[1] && param[1].rows[0]) {
                let bodyValues = param[1].rows[0].values;
                metaData[bodyArea].items.forEach((item) => {

                    let attrCode = item.attrcode;
                    if (item.initialvalue && bodyValues[attrCode]) {
                        let newValue = bodyValues[attrCode].value;
                        let newDisplay = bodyValues[attrCode].display || newValue;
                        if (item.itemtype == 'number') {
                            item.initialvalue.scale = bodyValues[attrCode].scale;
                            //一下特殊处理
                            if (item.attrcode == 'org_currinfo') { ///组织本币汇率
                                item.initialvalue.value = newValue;
                                item.initialvalue.display = newDisplay;
                            }
                        } 
                        // else {
                        //     item.initialvalue = {
                        //         value: newValue,
                        //         display: newDisplay
                        //     };
                        // }
                    }
                });
                this.props.meta.setMeta(metaData);
            }

            cardTable.setTableData(...param);
        }

        //重写cardTable 批量设置数据方法
        /* let oldSetMulTablesData = cardTable.setMulTablesData;
        cardTable.setMulTablesData = (...param) => {
            oldSetMulTablesData.apply(cardTable, param)
            let data = param[0];
            for (let tableAreaId in data) {
                window.__ssc_BillStyleVar.tableRowAndItemCount(tableAreaId, cardTable);
            }
        } */
    }

    componentDidMount() {
        getMultiLang({
            moduleId: 1056, domainName: 'sscrp', currentLocale: 'zh-CN', callback: (json) => {
                this.setState({
                    multiLang: json
                });
            }
        })

    }

    render() {
        let billHead = null;
        let billBody = null;

        let profileLayoutList = {
            oneMasterOneSlave: 'oneMasterOneSlave', //一主一子
            oneMasterMultiSlave: 'oneMasterMultiSlave' //一主多子
        }
        let { children, layout, ...otherProps } = this.props;

        otherProps = {
            layout,
            profileLayoutList,
            ncProps: otherProps,
        }
        let billBodyProps = {
            ...otherProps,
            sumText: this.state.sumText,
            multiLang: this.state.multiLang
        }

        React.Children.forEach(children, (child) => {
            if (typeof child.type == 'function') {

                switch (child.type.comName) { //此处获取函数名不兼容。后续处理
                    case 'BillHead':
                        billHead = React.cloneElement(child, otherProps);
                        break;
                    case 'BillBody':
                        billBody = React.cloneElement(child, billBodyProps);
                        break;
                    default:
                        console.warn('BillStyle组件仅接受BillHead和BillBody子组件')
                }
            }

        });
        return (
            <div className="nc-bill-card">
                {billHead}
                {billBody}
                {
                    // 联查审批情况 
                    (this.props.approveDetail || {}).show && <ApproveDetail
                        show={true}
                        close={this.props.approveDetail.close}
                        billtype={this.props.approveDetail.billtype}
                        billid={this.props.approveDetail.billid}
                    />
                }
                {
                    // 附件
                    (this.props.showUploader || {}).show && (
                        < NCUploader
                            disableButton={this.props.showUploader.uploaderBtn}
                            billId={this.props.showUploader.billid}
                            onHide={this.props.showUploader.close}
                        />
                    )
                }
            </div>
        )
    }
}

export default BillCardStyle
